from django.contrib import auth
import client
import datetime
import sys
sys.path.append('../')
import settings
NAME = getattr(settings,'AUTHENTICATION_NAME','django')


AUTH_KEY = '_auth_username'
AUTH_TOKEN = '_auth_session_key'

def login(request,user):
    if not hasattr(settings,'AUTH_D'):
        setattr(settings,'AUTH_D',client.authenticate(NAME))
    AUTH_D = settings.AUTH_D

    if user is None:
        user = request.user
    user.last_login = datetime.datetime.now()

    if AUTH_KEY in request.session:
        if request.session[AUTH_KEY] != user.username:
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[AUTH_KEY] = user.username
    
    try:
        sesskey = client.callfunc(AUTH_D,'new_session_key',(user.username,))
        if sesskey[0] == 0:
            request.session[AUTH_TOKEN] = sesskey[1]
        else:
            from django.contrib.auth.models import AnonymousUser
            user = AnonymousUser()
            request.user = user
            request.session.flush()
    except:
        request.session.flush()

    if hasattr(request, 'user'):
        request.user = user


def logout(request):
    try:

        if not hasattr(settings,'AUTH_D'):
            setattr(settings,'AUTH_D',client.authenticate(NAME))
        AUTH_D = settings.AUTH_D
        client.callfunc(AUTH_D,'delete_session',(user.username,))
    except:
        pass
    request.session.flush()
    if hasattr(request,'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()


def _get_user(f):
    def get_user(request):
        if not hasattr(settings,'AUTH_D'):
            setattr(settings,'AUTH_D',client.authenticate(NAME))
        AUTH_D = settings.AUTH_D
        from django.contrib.auth.models import AnonymousUser
        try:
            username = request.session[AUTH_KEY]
            userkey = request.session[AUTH_TOKEN]
            if client.auth_token(AUTH_D,username,userkey):
                profile = client.get_profile(AUTH_D,username)
                if 'email' in profile:
                    email = profile['email']
                else:
                    email = ''
                user =  client.create_user(username,email,d=profile)
                for key in profile:
                    if hasattr(user,key):
                        setattr(user,key,profile[key])
                return user
        except:
            return AnonymousUser()
    return get_user

#todo - change this to a wrapper so we have access to the original func
auth.login = login
auth.logout = logout
auth.get_user = _get_user(auth.get_user)

